package org.logan.sample.web.main.action;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.logan.sample.base.utils.json.JsonHandler;
import org.logan.sample.db.model.SysUser;
import org.logan.sample.web.main.action.common.BaseController;
import org.logan.sample.web.main.service.common.SysConfigs;
import org.logan.sample.web.main.service.system.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Desc：系统登录控制层
 * @Title：LoginController
 * @address: http://www.liveneo.com.cn/
 * @author: zhaoyy
 * @version: 1.0
 * @date: 2016年11月2日 下午1:51:04
 */
@Controller
public class LoginController extends BaseController {
    private final Logger   logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    SysConfigs             sysConfigs;

    /**
     * @Desc: 初始化登录页
     * @Author: zhaoyy 2016年11月2日 下午3:31:50
     * @param model
     * @return
     */
    @RequestMapping(value = "/login.html", method = RequestMethod.GET)
    public String login(ModelMap model) {
        // SysUser su = sysUserService.queryUserByAccount("admin@sample.org");
        // logger.debug("----------------------");
        // logger.debug(su.getUserMobile());
        // logger.debug("redis 是否启用：" + sysConfigs.getSysEnableItems().get("redis") + "");
        // sysConfigs.getSysEnableItems().put("redis", false);
        // logger.debug("redis 是否启用：" + sysConfigs.getSysEnableItems().get("redis") + "");
        // logger.debug("----------------------");
        return "pager/login";
    }

    /**
     * @Desc: 初始化登录页
     * @Author: zhaoyy 2016年11月2日 下午3:32:59
     * @param model
     * @return
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String _login(ModelMap model) {
        // SysUser su = sysUserService.queryUserByAccount("admin@sample.org");
        // logger.debug("----------------------");
        // logger.debug(su.getUserMobile());
        // logger.debug("redis 是否启用：" + sysConfigs.getSysEnableItems().get("redis") + "");
        // sysConfigs.getSysEnableItems().put("redis", false);
        // logger.debug("redis 是否启用：" + sysConfigs.getSysEnableItems().get("redis") + "");
        // logger.debug("----------------------");
        return "pager/login";
    }

    /**
     * @Desc: 登录系统
     * @Author: zhaoyy 2016年11月2日 下午3:33:50
     * @param username
     * @param password
     * @param request
     * @param model
     * @return
     * @throws IOException 
     * @throws ServletException 
     */
    @ResponseBody
    @RequestMapping(value = "/login.html", method = RequestMethod.POST)
    public Object _login(String username, String password, HttpServletRequest request, Boolean rememberMe, HttpServletResponse response, ModelMap model) {
        Map<String, Object> result = getResultMap();
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        token.setRememberMe((rememberMe == null ? false : rememberMe));
        try {
            if (subject.isAuthenticated()) {// 重复登录
                SysUser user = getUser();
                if (!user.getUserName().equals(username)) {// 如果登录名不同
                    subject.logout();
                    subject.login(token);
                }
            } else {
                subject.login(token);
            }
            result.put(RESULT, true);
        } catch (AccountException e) {
            result.put(RESULT, false);
            result.put(MESSAGE, "账号不存在或未激活！");
            token.clear();
        } catch (AuthenticationException e) {
            result.put(RESULT, false);
            result.put(MESSAGE, "账号或密码错误！");
            token.clear();
        }
        return JsonHandler.jsonstrFromObj(result);
    }

    /**
     * @Desc: 退出系统
     * @Author: zhaoyy 2016年11月2日 下午3:36:10
     * @param response
     */
    @RequestMapping(value = "/logout.html", method = RequestMethod.GET)
    public void logout(HttpServletResponse response) {
        SecurityUtils.getSubject().logout();
        try {
            response.sendRedirect("pager/login.html");
        } catch (IOException e) {
        }
    }

    /**
     * @Desc: 首页
     * @Author: zhaoyy 2016年11月2日 下午3:37:21
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/main.html", method = RequestMethod.GET)
    public String main(HttpServletRequest request, ModelMap model) {
        SysUser user = getUser();
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        model.put("sysDate", format.format(Calendar.getInstance().getTime()));
        model.put("user", user);
        model.put("menus", user.getMenus());    // 菜单和权限
        System.err.println(JsonHandler.jsonstrFromObj(user.getMenus()));
        return "pager/main";
    }

    @RequestMapping(value = "/homePage.html", method = RequestMethod.GET)
    public String homePage(HttpServletRequest request, ModelMap model) {
        SysUser user = getUser();
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        model.put("sysDate", format.format(Calendar.getInstance().getTime()));
        model.put("user", user);
        model.put("menus", user.getMenus());    // 菜单和权限
        System.err.println(JsonHandler.jsonstrFromObj(user.getMenus()));
        return "pager/homePage";
    }
}
